﻿using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using Abp.Timing;
using Microsoft.EntityFrameworkCore;

namespace SimpleCmsWithAbp.EntityFrameworkCore.Seed.Host
{
    public class DefaultApplicationLanguageTextCreator
    {
        public static List<ApplicationLanguageText> InitialLanguageTexts => GetInitialLanguageTexts();

        private readonly SimpleCmsWithAbpDbContext _context;
        private const string DefaultLanguageName = "zh-CN";

        private static List<ApplicationLanguageText> GetInitialLanguageTexts()
        {
            return new List<ApplicationLanguageText>
            {
                new ApplicationLanguageText()
                {
                    CreationTime = Clock.Now,
                    Source = SimpleCmsWithAbpConsts.LocalizationSourceName,
                    LanguageName = DefaultLanguageName,
                    Key = "verifyCodeInvalid",
                    Value = "验证码错误"
                },
                new ApplicationLanguageText()
                {
                    CreationTime = Clock.Now,
                    Source = SimpleCmsWithAbpConsts.LocalizationSourceName,
                    LanguageName = DefaultLanguageName,
                    Key = "UserManagement",
                    Value = "用户管理"
                },
                new ApplicationLanguageText()
                {
                    CreationTime = Clock.Now,
                    Source = SimpleCmsWithAbpConsts.LocalizationSourceName,
                    LanguageName = DefaultLanguageName,
                    Key = "ArticleManagement",
                    Value = "文章管理"
                },
                new ApplicationLanguageText()
                {
                    CreationTime = Clock.Now,
                    Source = SimpleCmsWithAbpConsts.LocalizationSourceName,
                    LanguageName = DefaultLanguageName,
                    Key = "MediaManagement",
                    Value = "媒体管理"
                },

            };
        }

        public DefaultApplicationLanguageTextCreator(SimpleCmsWithAbpDbContext context)
        {
            _context = context;
        }

        public void Create()
        {
            CreateLanguages();
        }

        private void CreateLanguages()
        {
            foreach (var languageText in InitialLanguageTexts)
            {
                AddLanguageIfNotExists(languageText);
            }
        }

        private void AddLanguageIfNotExists(ApplicationLanguageText languageText)
        {
            if (_context.LanguageTexts.IgnoreQueryFilters().Any(m=>m.LanguageName == languageText.LanguageName && m.Key == languageText.Key ))
            {
                return;
            }

            _context.LanguageTexts.Add(languageText);

            _context.SaveChanges();
        }

    }
}